﻿namespace Unity.Tools
{
    using Microsoft.Practices.Unity;
    using System;
    using System.Web;

    public class HttpContextLifetimeManager : LifetimeManager, IDisposable
    {
        private string key;

        public HttpContextLifetimeManager(string key)
        {
            this.key = key;
        }

        public override object GetValue()
        {
            return HttpContext.Current.Items[key];
        }

        public override void RemoveValue()
        {
            if (HttpContext.Current != null)
            {
                var item = HttpContext.Current.Items[key] as IDisposable;

                HttpContext.Current.Items.Remove(key);

                if (item != null)
                {
                    try
                    {
                        item.Dispose();
                    }
                    catch
                    {
                        // Nothing
                    }
                }
            }
        }

        public override void SetValue(object newValue)
        {
            HttpContext.Current.Items[key] = newValue;
        }

        public void Dispose()
        {
            RemoveValue();
        }
    }
}
